package com.cyh.blog.util;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class QiNiu {

    //设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "I8jvyqXUniqzQfPiHttRJMY03ws4npISoALPMDkP";
    String SECRET_KEY = "NZlWmnBUeBSqQeTlDKDRjSbpZ-aib1mQFoPF5ahe";
    //要上传的空间名--
    String bucketname = "chenqian";


    String key = "";

    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    //创建上传对象


    UploadManager uploadManager = new UploadManager(new Configuration());


    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    /**
     * @param FilePath 本地文件路径
     * @return 保存的文件名称
     * @throws IOException
     */
    public String upload(String FilePath) throws IOException {

        String[] split = FilePath.split("\\.");

        //通过日期生成图片名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        key = sdf.format(new Date());
        key += (int)(Math.random()*1000);
        key += "."+split[split.length-1];

        try {
            System.out.println(FilePath);
            //调用put方法上传
            Response res = uploadManager.put(FilePath, key, getUpToken());
            //打印返回的信息
            System.out.println(res.bodyString());
            System.out.println(res.statusCode);//200为上传成功
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
            }
        }
        return "http://p77ivlkgj.bkt.clouddn.com/"+key;  //返回图片地址
    }

    /**
     * 通过输入流上传
     * @param inputStream
     * @return
     * @throws IOException
     */
    public String upload(InputStream inputStream) throws IOException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        key = sdf.format(new Date());
        key += (int)(Math.random()*1000);

        try {
            byte[] uploadBytes = new byte[inputStream.available()];

            inputStream.read(uploadBytes);

            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String upToken = auth.uploadToken(bucketname);
            try {
                Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {

        }
        return "http://p77ivlkgj.bkt.clouddn.com/"+key;
    }

    public static void main(String[] args) throws IOException {
       InputStream input = new FileInputStream("D:\\360Downloads\\a2.jpg");
       new QiNiu().upload(input);
    }
}

